package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : xyq
 * @Description: Feign远程调用的请求拦截器（解决Feign远程调用丢失请求头问题）
 * @date: 2020/8/11/12:25
 */
@Configuration
public class GuliFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //1、使用RequestContextHolder 获取刚进来的请求数据
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest();    // 老请求
                if (request != null) {
                    //2、同步请求头的数据（cookie）
                    String cookie = request.getHeader("Cookie");
                    //把老请求的cookie值放到新请求上来，进行一个同步
                    template.header("Cookie", cookie);
                }
            }
        };
        return requestInterceptor;
    }
}
